const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async indexAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 10;
    const name = this.get('name') || '';

    const model = this.model('goods');
    const data = await model.where({name: ['like', `%${name}%`]}).order(['id DESC']).page(page, size).countSelect();

    return this.success(data);
  }

  async infoAction() {
    const id = this.get('id');
    const model = this.model('goods');
    const data = await model.where({id: id}).find();

    return this.success(data);
  }

  /**
   * 获取分类下的商品
   * @returns {Promise.<*>}
   */
  async getAllCategoryAction() {
    var _this2 = this;
    const pid = _this2.get('pid') || 0;
    const model = _this2.model('category');
    const data = await model.field(['id', 'name']).where({parent_id: pid}).select();
    return _this2.success(data);
  }

  async storeAction() {
    if (!this.isPost) {
      return false;
    }

    const values = this.post();
    const id = this.post('id');

    const model = this.model('goods');
    const productmodel = this.model('product');
    // values.is_on_sale = values.is_on_sale ? 1 : 0;
    values.is_new = values.is_new ? 1 : 0;
    values.is_hot = values.is_hot ? 1 : 0;
    if (id > 0) {
      await model.where({id: id}).update(values);
    } else {
      delete values.id;
      //20190108 刘立智 保存商品后，立即添加sku
      await model.add(values).then(async function(insertId) {
        const productvalues={goods_id:insertId,goods_specification_ids:'',goods_sn:values.goods_sn,goods_number:values.goods_number,retail_price:values.retail_price};

        await productmodel.add(productvalues);
      });
    }
    return this.success(values);
  }

  async destoryAction() {
    const id = this.post('id');
    await this.model('goods').where({id: id}).limit(1).delete();
    // TODO 删除图片

    return this.success();
  }
};
